<template>
  <div>
    <home>
      <div slot="conter" class="topaa" data-attr="编辑专场">
        <a href="#">
          <h2>编辑专场</h2>
        </a>
      </div>
      <div slot="context">
        <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">
          <span>请先删除原先封面</span>
          <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
        </el-dialog>
        <el-form :model="auction_list" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="商品标题" prop="title">
            <el-input v-model="auction_list.title"></el-input>
          </el-form-item>
          <el-form-item label="商品状态" prop="status">
            <el-select v-model="auction_list.status" placeholder="请选择活动区域">
              <el-option label="未开拍" value="1"></el-option>
              <el-option label="预展中" value="2"></el-option>
              <el-option label="拍卖中" value="3"></el-option>
              <el-option label="已结束" value="4"></el-option>

            </el-select>
          </el-form-item>
          <el-form-item label="预展时间" prop="preview_time">
            <el-date-picker
                    v-model="auction_list.preview_time"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="拍卖时间" prop="auction_time">
            <el-date-picker
                    v-model="auction_list.auction_time"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="全场保证金" prop="deposit">
            <el-input type="number" min="1000" v-model="auction_list.deposit" placeholder="全场保证金"></el-input>
          </el-form-item>
          <el-form-item label="封面" prop="type">
            <el-upload
                    class="upload-demo"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :http-request="handleChange"
                    :on-remove="handleRemove"
                    :limit=1
                    :file-list="fileList"
                    :on-exceed="LimitClick"
                    list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>

      </div>
    </home>
  </div>
</template>

<script>
  import Home from "./Home";
  import COS from "cos-js-sdk-v5";
  import {TX_COS, AddHomeAuction} from "network/home"

  export default {
    name: "HomeEdit",
    components: {Home},
    created() {
      this.auction_list = this.$route.query
      this.fileList[0].name = this.auction_list.cover.split('/').slice(-1)[0]
      this.fileList[0].url = this.auction_list.cover
    },
    data() {
      return {
        rules: {
          title: [
            {required: true, message: '请输入商品标题', trigger: 'blur'},
            {min: 5, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          ],
          status: [
            {required: true, message: '请选择拍卖状态', trigger: 'change'}
          ],
          preview_time: [
            {required: true, message: '请选择时间日期', trigger: 'change'}
          ],
          auction_time: [
            {required: true, message: '请选择时间日期', trigger: 'change'}
          ],
          deposit: [
            {required: true, message: '请输入全场保证金', trigger: 'change'}
          ],
          type: [{
            required: true, trigger: 'change', validator: this.valiimage
          }],
        },
        auction_list: [],
        fileList: [{name: '', url: '', file: ''}],
        dialogVisible: false,
        files: null
      };
    },
    methods: {
      valiimage(rule, value, callback) {
        if (!this.fileList[0]) {
          callback(new Error('请上传封面图片'));
        } else {
          callback()
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.auction_list['preview_start_time'] = this.auction_list.preview_time[0]
            this.auction_list['preview_end_time'] = this.auction_list.preview_time[1]
            this.auction_list['auction_start_time'] = this.auction_list.auction_time[0]
            this.auction_list['auction_end_time'] = this.auction_list.auction_time[1]
            if (this.files) {
              let that = this
              TX_COS().then(data => {
                const cos = new COS({
                  // 必选参数
                  getAuthorization: (options, callback) => {
                    const obj = {
                      TmpSecretId: data.credentials.tmpSecretId,
                      TmpSecretKey: data.credentials.tmpSecretKey,
                      XCosSecurityToken: data.credentials.sessionToken,
                      StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
                      ExpiredTime: data.expiredTime // 时间戳，单位秒，如：1580000900
                    }
                    callback(obj)
                  }
                })
                cos.deleteObject({
                  Bucket: 'wx-1304867879', /* 必须 */
                  Region: 'ap-guangzhou',     /* 存储桶所在地域，必须字段 */
                  Key: this.files        /* 必须 */
                }, function (err, data) {
                  console.log(err || data);
                  cos.putObject({
                    Bucket: 'wx-1304867879', /* 必须 */
                    Region: 'ap-guangzhou',     /* 存储桶所在地域，必须字段 */
                    Key: that.fileList[0].name,              /* 必须 */
                    StorageClass: 'STANDARD',
                    Body: that.fileList[0].file, // 上传文件对象
                    onProgress: function (progressData) {

                      console.log(JSON.stringify(progressData));
                    }
                  }, function (err, data) {
                    that.auction_list.cover = 'https://wx-1304867879.cos.ap-guangzhou.myqcloud.com/' + that.fileList[0].name
                    that.fileList[0].url = that.auction_list.cover

                    AddHomeAuction(that.auction_list).then(res => {
                      if (res.status) {
                        that.$router.push('/home').catch(err => {
                        })
                        console.log(res.message);
                      } else {
                        console.log(res.message);
                      }
                    }, err => {
                      console.log(err);
                    })
                  });
                });

              })
            } else {
              AddHomeAuction(this.auction_list).then(res => {
                if (res.status) {
                  this.$router.push('/home').catch(err => {
                  })
                  console.log(res.message);
                } else {
                  console.log(res.message);
                }
              }, err => {
                console.log(err);
              })
            }

          } else {
            console.log(valid);
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // 获取文件对象
      handleChange(file, fileList) {
        this.fileList[0].file = file.file
        this.fileList[0].name = this.randomString() + '.jpg'
      },
      randomString() {
        return Math.random().toString(36).slice(-8) + String(new Date().getTime())
      },
      handleRemove(file, fileList) {
        if (!this.files) {
          this.files = file.name
        }
        console.log(file.name, this.files);

      },
      handleClose(done) {
        this.$confirm('确认关闭？')
            .then(_ => {
              done();
            })
            .catch(_ => {
            });
      },
      LimitClick(file, fileList) {
        console.log("超过上传");
        this.dialogVisible = true
      }
    }

  }
</script>

<style scoped>
  .demo-ruleForm {
    width: 50%;
    height: 700px;
    margin: 0 auto;
    padding: 70px;
    background-color: #ffffff;
    border-top: 1px solid #eaeefb;
  }

</style>